package com.example.orderconsumer.consumer;

import com.example.orderconsumer.bean.Order;
import com.example.orderconsumer.dao.OrderDao;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName OrderConsumer
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/7/6
 * @Version 1.0.0
 */
@Component
@RocketMQMessageListener(consumerGroup = "order-consumer-01",topic = "order-topic")
public class OrderConsumer  implements RocketMQListener<String> {


    public static final String LOCK_STOCK_LUA=  "local counter = redis.call('hget',KEYS[1],ARGV[1]); \n" +
            "local result  = counter - ARGV[2];" +
            "if(result>=0 ) then \n" +
            "   redis.call('hset',KEYS[1],ARGV[1],result);\n" +
            "   redis.call('hincrby',KEYS[1],ARGV[3],ARGV[2]);\n" +
            "   return 1;\n" +
            "end;\n" +
            "return 0;\n";

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(String orderNo) {
        Order order = new Order();
        order.setOrderNo(orderNo);
        Optional<Order> one = orderDao.findOne(Example.of(order));
        if(one.isPresent()){
            return;
        }
        DefaultRedisScript<Long> stringRedisScript = new DefaultRedisScript<>();
        stringRedisScript.setScriptText(LOCK_STOCK_LUA);
        stringRedisScript.setResultType(Long.class);

        RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();

        //定义key
        List<String> keyList = new ArrayList<String>();
        keyList.add("ORDER-STOCK");
        Long restult = (Long)redisTemplate.execute(stringRedisScript,stringRedisSerializer,
                stringRedisSerializer,keyList,"RESIDUE-STOCK","1","PRESELL-STOCK");

        System.out.println(restult);
        System.out.println(restult.equals(0));
             if(restult.equals(0L)){
            System.out.println("库存不够，创建订单失败，秒杀已结束");
            return;
        }else{
            order.setStatus(1);
            orderDao.save(order);
        }

        //等待付款，放入延时队列
        SendResult sendResult = rocketMQTemplate.syncSend("delay-order", MessageBuilder.withPayload(orderNo).build(), 1000, 4);
        System.out.println(sendResult.getSendStatus());
    }
}

